package cn.dancepeak.service.impl;

import cn.dancepeak.domain.Login;
import cn.dancepeak.mapper.LoginMapper;
import cn.dancepeak.service.ILoginServiceImpl;
import cn.hutool.core.util.ObjectUtil;
import cn.dancepeak.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class LoginServiceImplImpl implements ILoginServiceImpl {
    @Autowired
    private LoginMapper loginMapper;


    private ConcurrentHashMap<String, Login> map = new ConcurrentHashMap<String, Login>();

    public ConcurrentHashMap<String, Login> getMap() {
        return map;
    }

    @Override
    public String account(Login login) {
        String username = login.getUsername();
        String password = login.getPassword();
        //判断用户名密码是否为空
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            //抛出自定义异常
            throw new BusinessException("用户名或密码不能为空");
        }
        //根据用户名查询数据库  看是否存在
        Login tmp = loginMapper.selectLogin(username);
        //用户名不存在  报错
        if(ObjectUtil.isNull(tmp)){
            throw new BusinessException("无法查询到用户");
        }
        //用户名存在 密码是否正确
        if(!password.equals(tmp.getPassword())){
            //密码错误  报错
            throw new BusinessException("用户名或密码错误");
        }
        //密码正确  登录信息储存到ConcurrentHashMap中 k为token
        UUID uuid = UUID.randomUUID();
        map.put(uuid.toString(),login);

        return uuid.toString();
    }
}
